The Practical Client
Generate TypeScript Classes from C# with TypeScriptSyntaxPaste
When working with TypeScript it's not unusual to need a class that matches an already existing server-side class written in C#. Here's one way to get from C# to TypeScript by doing what you normally do.
I often find myself passing a C# object created on the server to some TypeScript code so that the object's data can be used on the client. To facilitate that, I need a TypeScript object to use on the client that has identical properties to my C# object. I can't reuse C# objects in TypeScript, of course, but it would be great if I could just copy and paste my C# class from into my TypeScript code.
Which is exactly what TypeScriptSyntaxPaste does. There's only one major limitation: TypeScriptSyntaxPaste needs the Rosalyn compiler, which means it's only available in Visual Studio 2015.
To use TypeScriptSyntaxPaste, you just need to install it from the Visual Studio Tools | Extensions menu. Once you've installed TypeScriptSyntaxPaste, the utility is pretty much invisible. It's just that, from now on, whenever you copy some C# code and paste it into a TypeScript file (either .ts or .tsx), TypeScriptSyntaxPaste will step in and make a good faith effort to convert that C# code to TypeScript.
Because all I want are the property definitions from my C# class, I usually just have to delete some of the TypeScriptSyntaxPaste generated code to get the TypeScript class I want. For example, if I copy this C# class:
public class MyClass
{
private string Id;
public MyClass(string Id)
{
this.Id = Id;
}
public string prop1 { get; set; }
public string prop2 { get; set; }
}
I get this TypeScript class when I paste into a TypeScript file:
export class MyClass {
private Id: string;
constructor(Id: string) {
this Id = Id;
}
public prop1: string;
public prop2: string;
}
Because all I want are the property definitions, I just need to delete the constructor out of this class.
You can tweak how TypeScriptSyntaxPaste transforms your code in Tools | Options | TypeScript Paste. TypeScriptSyntaxPaste lets you specify that you want to have an interface rather than a class generated when you paste; you can also have all C# Lists converted to TypeScript arrays. Even with those tweaks, for any interesting class, I suspect you'll need to do some editing to get the TypeScript code you want. But you'll have far less work to do and far less chance of accidentally forgetting some property if you use TypeScriptSyntaxPaste. I just wish it worked with Visual Basic, too.
About the Author
Peter Vogel is a system architect and principal in PH&V Information Services. PH&V provides full-stack consulting from UX design through object modeling to database design. Peter tweets about his VSM columns with the hashtag #vogelarticles. His blog posts on user experience design can be found at http://blog.learningtree.com/tag/ui/.